package com.jsjosem.aftersales.ui.notifications;

import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jsjosem.aftersales.R;
import com.jsjosem.aftersales.adapter.ServiceNotifyAdapter;
import com.jsjosem.aftersales.api.NotificationsApi;
import com.jsjosem.aftersales.api.RetrofitClient;
import com.jsjosem.aftersales.data.response.BaseResponse;
import com.jsjosem.aftersales.data.response.NotificationsResponse;
import com.jsjosem.aftersales.data.response.PageResponse;
import com.jsjosem.aftersales.request.AsyncRequest;
import com.jsjosem.aftersales.utils.PageUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Retrofit;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ServiceNotifyListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ServiceNotifyListFragment extends Fragment {

    private Context context;
    private RecyclerView recyclerView;
    private ServiceNotifyAdapter serviceNotifyAdapter;
    private List<NotificationsResponse> serviceNotifies = new ArrayList<>();
    private SmartRefreshLayout smartRefreshLayout;
    private Retrofit mRetrofit = RetrofitClient.getInstance();
    private NotificationsApi eventApi = mRetrofit.create(NotificationsApi.class);
    private Dialog loadingDialog;
    private final static int PAGE_SIZE = 10;
    private int currentPage = 1;

    public ServiceNotifyListFragment() {
    }

    public static ServiceNotifyListFragment newInstance() {
        return new ServiceNotifyListFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_page_list, container, false);
        context = view.getContext();
        initView(view);
        loadingShow();
        initData(currentPage++);
        initPageList();
        loadMore();
        return view;
    }

    private void initPageList() {
        serviceNotifyAdapter = new ServiceNotifyAdapter(context, serviceNotifies);
        serviceNotifyAdapter.setOnItemClickListener((v, position) -> {
            NotificationsResponse eventResponse = serviceNotifies.get(position);
            Intent intent = new Intent(getContext(), ServiceEventInfoActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("eventId", String.valueOf(eventResponse.getmBusinessId()));
            intent.putExtras(bundle);
            Call<BaseResponse<Void>> events = eventApi.markRead(eventResponse.getmId());
            AsyncRequest<BaseResponse<Void>> request = new AsyncRequest<>();
            request.sendRequest(events, res -> {
                serviceNotifies.get(position).setmStatus(Long.parseLong("1"));
                serviceNotifyAdapter.notifyItemChanged(position);
                Log.d(TAG, "标记通知已读成功");
            }, errMsg -> Toast.makeText(context, errMsg.toString(), Toast.LENGTH_SHORT).show());
            startActivity(intent);
        });
        recyclerView.setAdapter(serviceNotifyAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
    }

    private void initView(View view) {
        smartRefreshLayout = view.findViewById(R.id.refreshLayout);
        smartRefreshLayout.setEnableAutoLoadMore(false);
        recyclerView = view.findViewById(R.id.ticket_recycler_view);
    }


    private void loadMore() {
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            /**
             * 加载更多
             * @param refreshLayout
             */
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                initData(currentPage++);
                smartRefreshLayout.finishLoadMore();
            }

            /**
             * 下拉刷新
             * @param refreshLayout
             */
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                serviceNotifies.clear();
                initData(currentPage++);
                smartRefreshLayout.finishRefresh();
            }
        });
    }

    private void initData(int currentPage) {
        Call<PageResponse<NotificationsResponse>> eventsNotifications = eventApi.getNotificationsByPage("event", currentPage, PAGE_SIZE);
        AsyncRequest<PageResponse<NotificationsResponse>> request = new AsyncRequest<>();
        request.sendRequest(eventsNotifications, (res) -> {
            if (res != null) {
                Long total = res.getCount();
                int totalPage = PageUtils.totalPage(PAGE_SIZE, total);
                if (currentPage > totalPage) {
                    smartRefreshLayout.finishLoadMoreWithNoMoreData();
                } else {
                    List<NotificationsResponse> data = res.getData();
                    serviceNotifies.addAll(data);
                    loadingDialog.dismiss();
                    // 数据加载好后，初始化列表页
                    int size = serviceNotifies.size();
                    serviceNotifyAdapter.notifyDataSetChanged();
                }
            }
        }, failedMessage -> Toast.makeText(context, failedMessage.toString(), Toast.LENGTH_SHORT).show());
    }

    private void loadingShow() {
        loadingDialog = new Dialog(context, R.style.normal_dialog_style);
        View loadingView = View.inflate(context, R.layout.dialog_loading, null);
        loadingDialog.setContentView(loadingView);
        //使得点击对话框外部不消失对话框
        loadingDialog.setCanceledOnTouchOutside(false);
        AVLoadingIndicatorView avi = loadingView.findViewById(R.id.avi);
        avi.show();
        loadingDialog.show();
    }

}